<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=7.0.1">


  <link rel="mask-icon" href="/images/favicon.ico?v=7.0.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="概述H5页面，需要加入一个音乐，然后要对音乐进行开、关控制。 首先H5加入音乐的话，需要用到H5的audio标签。 然后为了在页面上做音乐开关的控制，替换了默认的音乐播放器的图片，找了一个漂亮的音乐icon替代。 为了音乐播放过程的美观，需要对音乐icon控制，音乐播放的时候，图片旋转，暂定的时候，图片停止旋转。因此用到Jquery的插件：JqueryRotate。">
<meta name="keywords" content="Jquery,JS,H5,HTML,JqueryRotate">
<meta property="og:type" content="article">
<meta property="og:title" content="h5 audio JS控制音乐开关">
<meta property="og:url" content="http://forkun.oschina.io/2016/11/24/h5-audio-JS控制音乐开关/index.html">
<meta property="og:site_name" content="forkun">
<meta property="og:description" content="概述H5页面，需要加入一个音乐，然后要对音乐进行开、关控制。 首先H5加入音乐的话，需要用到H5的audio标签。 然后为了在页面上做音乐开关的控制，替换了默认的音乐播放器的图片，找了一个漂亮的音乐icon替代。 为了音乐播放过程的美观，需要对音乐icon控制，音乐播放的时候，图片旋转，暂定的时候，图片停止旋转。因此用到Jquery的插件：JqueryRotate。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="">
<meta property="og:image" content="">
<meta property="og:updated_time" content="2019-04-09T07:03:32.166Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="h5 audio JS控制音乐开关">
<meta name="twitter:description" content="概述H5页面，需要加入一个音乐，然后要对音乐进行开、关控制。 首先H5加入音乐的话，需要用到H5的audio标签。 然后为了在页面上做音乐开关的控制，替换了默认的音乐播放器的图片，找了一个漂亮的音乐icon替代。 为了音乐播放过程的美观，需要对音乐icon控制，音乐播放的时候，图片旋转，暂定的时候，图片停止旋转。因此用到Jquery的插件：JqueryRotate。">
<meta name="twitter:image" content="">






  <link rel="canonical" href="http://forkun.oschina.io/2016/11/24/h5-audio-JS控制音乐开关/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>h5 audio JS控制音乐开关 | forkun</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">forkun</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://forkun.oschina.io/2016/11/24/h5-audio-JS控制音乐开关/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="forkun">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="forkun">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">h5 audio JS控制音乐开关

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2016-11-24 14:22:38" itemprop="dateCreated datePublished" datetime="2016-11-24T14:22:38+00:00">2016-11-24</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-04-09 07:03:32" itemprop="dateModified" datetime="2019-04-09T07:03:32+00:00">2019-04-09</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/前端技术/" itemprop="url" rel="index"><span itemprop="name">前端技术</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h4><p>H5页面，需要加入一个音乐，然后要对音乐进行开、关控制。</p>
<p>首先H5加入音乐的话，需要用到H5的audio标签。</p>
<p>然后为了在页面上做音乐开关的控制，替换了默认的音乐播放器的图片，找了一个漂亮的音乐icon替代。</p>
<p>为了音乐播放过程的美观，需要对音乐icon控制，音乐播放的时候，图片旋转，暂定的时候，图片停止旋转。因此用到Jquery的插件：<code>JqueryRotate</code>。</p>
<a id="more"></a>
<h4 id="H5-audio标签"><a href="#H5-audio标签" class="headerlink" title="H5-audio标签"></a>H5-audio标签</h4><h5 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h5><p>标签定义声音，比如音乐或者其他音频流。是HTML5的新标签。<br>由于老的浏览器不兼容。因此可以在<code>audio</code>标签之间，放置需要默认显示的内容<br>例如：<br><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">audio</span> <span class="attr">src</span>=<span class="string">"/path/test.mp3"</span>&gt;</span></span><br><span class="line">	您的浏览器不支持audio标签</span><br><span class="line"><span class="tag">&lt;/<span class="name">audio</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<h5 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h5><table>
<thead>
<tr>
<th>属性</th>
<th>值</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>autoplay</td>
<td>autoplay</td>
<td>如果出现该属性，则音频在就绪后，马上播放。</td>
</tr>
<tr>
<td>controls</td>
<td>controls</td>
<td>如果出现该属性，则向用户显示控件，比如播放器按钮等。</td>
</tr>
<tr>
<td>loop</td>
<td>loop</td>
<td>如果出现该属性，则每当音频结束时都会重新开始播放。</td>
</tr>
<tr>
<td>preload</td>
<td>preload</td>
<td>如果出现该属性，则音频在页面加载时进行加载，并预备播放。如果使用 “autoplay”，则忽略该属性。</td>
</tr>
<tr>
<td>src</td>
<td>url</td>
<td>要引用的音频文件的路径。</td>
</tr>
</tbody>
</table>
<h5 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h5><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">audio</span> <span class="attr">src</span>=<span class="string">"test.mp3"</span> <span class="attr">loop</span> <span class="attr">controls</span> <span class="attr">autoplay</span>=<span class="string">"autoplay"</span> <span class="attr">id</span>=<span class="string">"audio"</span>&gt;</span></span><br><span class="line">	您的浏览器不支持audio标签</span><br><span class="line"><span class="tag">&lt;/<span class="name">audio</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>该音频，会在该页面打开的时候，直接播放<code>test.mp3</code>文件，并且显示默认的控件。<br>最终真实效果：<br><img src="" alt="音频默认控件样式"></p>
<h4 id="JS-控制播放"><a href="#JS-控制播放" class="headerlink" title="JS-控制播放"></a>JS-控制播放</h4><h5 id="关于JS控制音频文件的事件，目前只整理2个"><a href="#关于JS控制音频文件的事件，目前只整理2个" class="headerlink" title="关于JS控制音频文件的事件，目前只整理2个"></a>关于JS控制音频文件的事件，目前只整理2个</h5><pre><code>1. play() 播放
2. pause() 暂停（非停止，再次播放，会连续上次的播放节点）
</code></pre><h5 id="示例-1"><a href="#示例-1" class="headerlink" title="示例"></a>示例</h5><ol>
<li><p>js示例代码</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">	<span class="keyword">var</span> audio = <span class="built_in">document</span>.getElementById(<span class="string">"audio"</span>);</span></span><br><span class="line"><span class="actionscript">	audio.play();	<span class="comment">//播放</span></span></span><br><span class="line"><span class="actionscript">	audio.pause();	<span class="comment">//暂停</span></span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>jquery示例代码</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">	<span class="keyword">var</span> audio = $(<span class="string">"#audio"</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="actionscript">	audio.play();	<span class="comment">//播放</span></span></span><br><span class="line"><span class="actionscript">	audio.pause();	<span class="comment">//暂停</span></span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<blockquote>
<p>其他说明：<br>JS操作获得的是audio对象，因此可以直接操作play、pause<br>Jquery选择器获取的是jquery对象，0才是对应的audio对象，所以不能直接操作。</p>
</blockquote>
<h4 id="JqueryRotate-图片旋转"><a href="#JqueryRotate-图片旋转" class="headerlink" title="JqueryRotate-图片旋转"></a>JqueryRotate-图片旋转</h4><h5 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h5><p>JqueryRotate，可以实现旋转效果的jquery插件。支持所有主流浏览器。<br>可以在其 <a href="http://jqueryrotate.com/" target="_blank" rel="noopener">官网</a> 获取下载资源以及使用案例。</p>
<h5 id="使用示例"><a href="#使用示例" class="headerlink" title="使用示例"></a>使用示例</h5><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./yinyue.png"</span> <span class="attr">alt</span>=<span class="string">""</span> <span class="attr">id</span>=<span class="string">"img"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"./jQueryRotate.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="actionscript">	<span class="comment">// 直接旋转45度（向右旋转）</span></span></span><br><span class="line"><span class="javascript">	$(<span class="string">'#img'</span>).rotate(<span class="number">45</span>);</span></span><br><span class="line"><span class="javascript">	$(<span class="string">'#img'</span>).rotate(&#123;<span class="attr">angle</span>:<span class="number">45</span>&#125;);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">	<span class="comment">// 鼠标事件控制：获取鼠标右转180度，鼠标离开回归原始</span></span></span><br><span class="line"><span class="javascript">	$(<span class="string">'#img'</span>).rotate(&#123; </span></span><br><span class="line"><span class="undefined">	    bind : &#123;</span></span><br><span class="line"><span class="actionscript">	        mouseover : <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript">	            $(<span class="keyword">this</span>).rotate(&#123;<span class="attr">animateTo</span>: <span class="number">180</span>&#125;);</span></span><br><span class="line"><span class="actionscript">	        &#125;, mouseout : <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript">	            $(<span class="keyword">this</span>).rotate(&#123;<span class="attr">animateTo</span>: <span class="number">0</span>&#125;);</span></span><br><span class="line"><span class="undefined">	        &#125;</span></span><br><span class="line"><span class="undefined">	    &#125;</span></span><br><span class="line"><span class="undefined">	&#125;);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">	<span class="comment">// 不停的旋转</span></span></span><br><span class="line"><span class="actionscript">	<span class="keyword">var</span> angle = <span class="number">0</span>;</span></span><br><span class="line"><span class="actionscript">	setInterval(<span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="undefined">	    angle +=3;</span></span><br><span class="line"><span class="javascript">	    $(<span class="string">'#img'</span>).rotate(angle);</span></span><br><span class="line"><span class="undefined">	&#125;, 15);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">	<span class="comment">// 间隔旋转，每次旋转都会有停顿</span></span></span><br><span class="line"><span class="actionscript">	<span class="keyword">var</span> rotation = <span class="function"><span class="keyword">function</span> <span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript">	    $(<span class="string">'#img'</span>).rotate(&#123;</span></span><br><span class="line"><span class="undefined">	        angle: 0, </span></span><br><span class="line"><span class="undefined">	        animateTo: 360, </span></span><br><span class="line"><span class="undefined">	        callback: rotation</span></span><br><span class="line"><span class="undefined">	    &#125;);</span></span><br><span class="line"><span class="undefined">	&#125;</span></span><br><span class="line"><span class="undefined">	rotation();</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">	<span class="comment">// 不停旋转，中间没有卡顿</span></span></span><br><span class="line"><span class="actionscript">	<span class="keyword">var</span> rotation2 = <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript">	    $(<span class="string">'#img'</span>).rotate(&#123;</span></span><br><span class="line"><span class="undefined">	        angle: 0, </span></span><br><span class="line"><span class="undefined">	        animateTo: 360, </span></span><br><span class="line"><span class="undefined">	        callback: rotation2,</span></span><br><span class="line"><span class="actionscript">	        easing: <span class="function"><span class="keyword">function</span><span class="params">(x,t,b,c,d)</span></span>&#123;</span></span><br><span class="line"><span class="actionscript">	            <span class="keyword">return</span> c*(t/d)+b;</span></span><br><span class="line"><span class="undefined">	        &#125;</span></span><br><span class="line"><span class="undefined">	    &#125;);</span></span><br><span class="line"><span class="undefined">	&#125;</span></span><br><span class="line"><span class="undefined">	rotation2();</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">	<span class="comment">// 点击旋转</span></span></span><br><span class="line"><span class="javascript">	$(<span class="string">'#img'</span>).rotate(&#123; </span></span><br><span class="line"><span class="undefined">	    bind: &#123;</span></span><br><span class="line"><span class="actionscript">	        click: <span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript">	            $(<span class="keyword">this</span>).rotate(&#123;</span></span><br><span class="line"><span class="undefined">	                angle: 0,</span></span><br><span class="line"><span class="undefined">	                animateTo: 360,</span></span><br><span class="line"><span class="javascript">	                easing: $.easing.easeInOutExpo</span></span><br><span class="line"><span class="undefined">	            &#125;);</span></span><br><span class="line"><span class="undefined">	        &#125;</span></span><br><span class="line"><span class="undefined">	    &#125;</span></span><br><span class="line"><span class="undefined">	&#125;);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h5 id="参数说明"><a href="#参数说明" class="headerlink" title="参数说明"></a>参数说明</h5><table>
<thead>
<tr>
<th>参数</th>
<th>类型</th>
<th>默认值</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>angle</td>
<td>数字</td>
<td>0</td>
<td>旋转一个角度</td>
</tr>
<tr>
<td>animateTo</td>
<td>数字</td>
<td>0</td>
<td>从当前的角度，旋转到多少度</td>
</tr>
<tr>
<td>step</td>
<td>函数</td>
<td>无</td>
<td>每个动画步骤中执行的回调函数，当前角度值作为该函数的第一个参数</td>
</tr>
<tr>
<td>easing</td>
<td>函数</td>
<td>无</td>
<td>定义旋转速度、旋转效果，但是需要加载：jQuery.easing.js</td>
</tr>
<tr>
<td>duration</td>
<td>整数</td>
<td>无</td>
<td>旋转持续时间，以毫秒为单位</td>
</tr>
<tr>
<td>callback</td>
<td>函数</td>
<td>无</td>
<td>旋转完成后的回调函数</td>
</tr>
<tr>
<td>getRotateAngle</td>
<td>函数</td>
<td>无</td>
<td>返回旋转对象的当前的旋转角度</td>
</tr>
<tr>
<td>stopRotate</td>
<td>函数</td>
<td>无</td>
<td>停止旋转</td>
</tr>
</tbody>
</table>
<blockquote>
<p>演示虽然使用的是图片，但 jqueryrotate 并不只是能运用在图片上，其他元素如 div 等也可以使用。</p>
</blockquote>
<h4 id="最终效果"><a href="#最终效果" class="headerlink" title="最终效果"></a>最终效果</h4><h5 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h5><ol>
<li>用audio标签，完成音频文件的引用，设置标签循环播放，不自动播放（让JS控制播放）</li>
<li>美化：将audio标签设置为隐藏<code>style=&quot;display:none;&quot;</code>，用其他图片代替，用图片的JS时间，控制播放、暂停</li>
<li>美化：用<code>jqueryrotate</code>插件美化图片的旋转效果，图片旋转随着音乐的播放和暂停来旋转和不旋转</li>
</ol>
<h5 id="源码"><a href="#源码" class="headerlink" title="源码"></a>源码</h5><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"yinyue.svg"</span> <span class="attr">alt</span>=<span class="string">""</span> <span class="attr">class</span>=<span class="string">"rotate"</span> <span class="attr">id</span>=<span class="string">"music_img"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">audio</span> <span class="attr">id</span>=<span class="string">"media"</span> <span class="attr">src</span>=<span class="string">"test.mp3"</span> <span class="attr">loop</span>=<span class="string">"loop"</span><span class="attr">style</span>=<span class="string">"display:none"</span>&gt;</span></span><br><span class="line">	您的浏览器不支持audio标签</span><br><span class="line"><span class="tag">&lt;/<span class="name">audio</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"jQueryRotate.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">	$(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">		<span class="keyword">if</span> ($(<span class="string">"#music_img"</span>).length &gt; <span class="number">0</span>) &#123;</span></span><br><span class="line"><span class="javascript">			<span class="keyword">var</span> Media = $(<span class="string">"#media"</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="javascript">			<span class="keyword">if</span> ($(<span class="string">"#music_img"</span>).hasClass(<span class="string">'rotate'</span>)) &#123;</span></span><br><span class="line"><span class="actionscript">				<span class="keyword">var</span> angle = <span class="number">0</span>;</span></span><br><span class="line"><span class="actionscript">				setInterval(<span class="function"><span class="keyword">function</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="undefined">					angle +=3;</span></span><br><span class="line"><span class="javascript">					$(<span class="string">'.rotate'</span>).rotate(angle);</span></span><br><span class="line"><span class="undefined">				&#125;, 15);</span></span><br><span class="line"><span class="undefined">				Media.play();</span></span><br><span class="line"><span class="undefined">			&#125;</span></span><br><span class="line"><span class="javascript">			$(<span class="string">"#music_img"</span>).on(<span class="string">"click"</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">				<span class="keyword">if</span> ($(<span class="keyword">this</span>).hasClass(<span class="string">'rotate'</span>)) &#123;</span></span><br><span class="line"><span class="undefined">					Media.pause();</span></span><br><span class="line"><span class="javascript">					$(<span class="keyword">this</span>).addClass(<span class="string">'off'</span>).removeClass(<span class="string">'rotate'</span>);</span></span><br><span class="line"><span class="actionscript">				&#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="undefined">					Media.play();</span></span><br><span class="line"><span class="javascript">					$(<span class="keyword">this</span>).addClass(<span class="string">'rotate'</span>).removeClass(<span class="string">'off'</span>);</span></span><br><span class="line"><span class="undefined">				&#125;</span></span><br><span class="line"><span class="undefined">			&#125;);</span></span><br><span class="line"><span class="undefined">		&#125;</span></span><br><span class="line"><span class="undefined">	&#125;);</span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h5 id="最终效果-1"><a href="#最终效果-1" class="headerlink" title="最终效果"></a>最终效果</h5><p><img src="" alt="音乐图片旋转效果"></p>
<blockquote>
<p>在静态图片上，显示不出旋转效果，其实图片是旋转的<br>点击旋转中的图标，图标停止旋转，音乐暂停<br>点击暂停的图标，图标开始旋转，音乐继续</p>
</blockquote>
<p>主要参考：<br><a href="http://www.tuicool.com/articles/ZfU7ju" target="_blank" rel="noopener">http://www.tuicool.com/articles/ZfU7ju</a><br><a href="http://www.dowebok.com/72.html" target="_blank" rel="noopener">http://www.dowebok.com/72.html</a><br><a href="http://www.w3school.com.cn/tags/tag_audio.asp" target="_blank" rel="noopener">http://www.w3school.com.cn/tags/tag_audio.asp</a></p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Jquery/" rel="tag"># Jquery</a>
          
            <a href="/tags/JS/" rel="tag"># JS</a>
          
            <a href="/tags/H5/" rel="tag"># H5</a>
          
            <a href="/tags/HTML/" rel="tag"># HTML</a>
          
            <a href="/tags/JqueryRotate/" rel="tag"># JqueryRotate</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/11/11/Thinkphp笔记/" rel="next" title="Thinkphp笔记">
                <i class="fa fa-chevron-left"></i> Thinkphp笔记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/12/23/Mysql数据库从库监控提醒/" rel="prev" title="Mysql数据库从库监控提醒">
                Mysql数据库从库监控提醒 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">forkun</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">25</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">23</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#概述"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#H5-audio标签"><span class="nav-number">2.</span> <span class="nav-text">H5-audio标签</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#说明"><span class="nav-number">2.1.</span> <span class="nav-text">说明</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#属性"><span class="nav-number">2.2.</span> <span class="nav-text">属性</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#示例"><span class="nav-number">2.3.</span> <span class="nav-text">示例</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#JS-控制播放"><span class="nav-number">3.</span> <span class="nav-text">JS-控制播放</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#关于JS控制音频文件的事件，目前只整理2个"><span class="nav-number">3.1.</span> <span class="nav-text">关于JS控制音频文件的事件，目前只整理2个</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#示例-1"><span class="nav-number">3.2.</span> <span class="nav-text">示例</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#JqueryRotate-图片旋转"><span class="nav-number">4.</span> <span class="nav-text">JqueryRotate-图片旋转</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#介绍"><span class="nav-number">4.1.</span> <span class="nav-text">介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#使用示例"><span class="nav-number">4.2.</span> <span class="nav-text">使用示例</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#参数说明"><span class="nav-number">4.3.</span> <span class="nav-text">参数说明</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#最终效果"><span class="nav-number">5.</span> <span class="nav-text">最终效果</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#思路"><span class="nav-number">5.1.</span> <span class="nav-text">思路</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#源码"><span class="nav-number">5.2.</span> <span class="nav-text">源码</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#最终效果-1"><span class="nav-number">5.3.</span> <span class="nav-text">最终效果</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">forkun</span>

  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.1"></script>

  <script src="/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.1"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.1"></script>



  
  <script src="/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

  

  

  

  

  

  

  

  

</body>
</html>
